/**
 * 存储localStorage
 */
export const setStorage = (name, value, expire) => {
  if (!name) return
  let content = {}
  if (!expire) {
    content = {
      value: value
    }
  } else {
    content = {
      value: value,
      time: (new Date()).getTime(),
      expire: expire * 1000 * 60
    }
  }
  content = JSON.stringify(content)

  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
export const getStorage = name => {
  if (!name) return

  let content = JSON.parse(window.localStorage.getItem(name))

  if (!content) return null

  if (content.time && ((new Date()).getTime() - content.time) > content.expire) {
    window.localStorage.removeItem(name)
    return null
  }
  return content.value
}

/**
 * 删除localStorage
 */
export const removeStorage = name => {
  if (!name) return
  window.localStorage.removeItem(name)
}

export default {
  install: function (Vue) {
    Object.defineProperties(Vue.prototype, {
      $util: {
        value: {
          setStorage,
          getStorage,
          removeStorage
        }
      }
    })
  }
}
